package com.cn.mmd.controller;

import com.cn.mmd.model.*;
import com.cn.mmd.service.*;
import com.cn.mmd.tools.AliyunOssUtil;
import com.cn.mmd.tools.GetLimitNum;
import com.cn.mmd.tools.PictureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/7/15 0015.
 */

@Controller
@RequestMapping(value = "page/activity")
public class StudentActivityController {

    @Autowired
    private StudentActivityService studentActivityService;

    @Autowired
    private ManageActivityService manageActivityService;

    @Autowired
    private TokenController tokenController;

    @Autowired
    private LogManageService logManageService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentCountController studentCountController;

    @Autowired
    private StudentCountService studentCountService;
    @Autowired
    private StudentIntegralController studentIntegralController;

    @RequestMapping(value = "/select")
    public synchronized
    @ResponseBody
    Object selectStudentActivity(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        List<Map> mapList = new ArrayList<Map>();
        Map<String, Object> map;
        String acitvityTitle = request.getParameter("activityTitle");
        Integer statrow = Integer.parseInt(request.getParameter("startrow"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String studentId = request.getParameter("studentId");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (statrow < 1) {
            statrow = 1;
        }
        statrow = (statrow - 1) * pageSize;
        Activity activity = new Activity();
        activity.setPageSize(pageSize);
        activity.setStartrow(statrow);
        activity.setAcitvitytitle(acitvityTitle);
        activity.setActivitytype("审核通过");
        if (studentApp != null) {
            List<Activity> activityList = studentActivityService.selectByActivityName(activity);
            if (activityList != null && activityList.size() > 0) {
                for (int i = 0; i < activityList.size(); i++) {
                    activity = activityList.get(i);
                    map = new HashMap<String, Object>();
                    map.put("activityTitle", activity.getAcitvitytitle());
//                map.put("activityContent", activity.getActivitycontent());
                    map.put("activityCollege", activity.getActivitycollege());
                    map.put("activityTime", activity.getActivitytime());
                    map.put("activityId", activity.getActivityid() + "");
                    map.put("activityLocation", activity.getActivitylocation());
                    map.put("activityPictureUrl", activity.getActivitypictureurl());
                    map.put("functionAttendance", activity.getFunctionattendance());
                    map.put("functionAttendanceSum", activity.getFunctionattendancesum());
                    mapList.add(map);
                }
                activity = new Activity();
                activity.setAcitvitytitle(acitvityTitle);
                int i1 = manageActivityService.countLimitNum(activity);
                objectMap.put("total", i1);
                objectMap.put("data", mapList);
                objectMap.put("message", "成功");
                objectMap.put("code", 200);
            } else {
                activity = new Activity();
                activity.setAcitvitytitle(acitvityTitle);
                int i1 = manageActivityService.countLimitNum(activity);
                objectMap.put("total", i1);
                objectMap.put("message", "查询失败");
                objectMap.put("code", 201);
            }
        } else {
            activity = new Activity();
            activity.setAcitvitytitle(acitvityTitle);
            int i1 = manageActivityService.countLimitNum(activity);
            objectMap.put("total", i1);
            objectMap.put("message", "此用户没有权限做此操作");
            objectMap.put("code", 202);
        }
        return objectMap;
    }


    @RequestMapping(value = "/selectOne")
    public synchronized
    @ResponseBody
    Object selectOneStudentActivity(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        Integer activityId = Integer.parseInt(request.getParameter("activityId"));
        String studentId = request.getParameter("studentId");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null) {
            Activity activity = studentActivityService.selectByPrimaryKey(activityId);
            if (activity != null) {
                Map<String, Object> maps = new HashMap<String, Object>();
                List<Map> urlList = new ArrayList();
                if (activity.getActivitypictureurls() != null && !activity.getActivitypictureurls().equals("")) {
                    String urls[] = activity.getActivitypictureurls().split(",");
                    String url;
                    Map<String, Object> map1;
                    if (urls == null) {
                        maps.put("url", urlList);
                    } else {
                        for (int i = 0; i < urls.length; i++) {
                            if (!urls[i].equals("")) {
                                map1 = new HashMap<String, Object>();
                                url = urls[i];
                                map1.put("activityPictureUrl", url);
                                urlList.add(map1);
                            }
                        }
                        maps.put("url", urlList);
                    }
                } else {
                    maps.put("url", urlList);
                }
                maps.put("content", activity.getActivitycontent());
                map.put("activityContent", maps);
                map.put("activityTime", activity.getActivitytime());
                map.put("activityLocation", activity.getActivitylocation());
                map.put("activityCollege", activity.getActivitycollege());
                map.put("activityTitle", activity.getAcitvitytitle());
                map.put("activityCollegeNumber", activity.getActivitycollegenumber());
                objectMap.put("data", map);
                objectMap.put("message", "成功");
                objectMap.put("code", 200);

            } else {
                objectMap.put("message", "失败没有获取到该id的活动信息");
                objectMap.put("code", 201);
            }
        } else {
            objectMap.put("code", 202);
            objectMap.put("message", "此用户没有权限做此操作");
        }
        return objectMap;
    }

    @RequestMapping(value = "/joinNum")
    public synchronized
    @ResponseBody
    Object joinNumStudentActivity(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        Integer activityId = Integer.parseInt(request.getParameter("activityId"));
        String studentId = request.getParameter("studentId");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null&&activityId!=null) {
            Activity activity1 = studentActivityService.selectByPrimaryKey(activityId);
            StudentActivity studentActivity = new StudentActivity();
            studentActivity.setActivityid(activityId);
            int n = studentActivityService.countByAll(studentActivity);
            studentActivity.setStuid(studentId);
            if (studentActivityService.countByIdsId(studentActivity) == null) {
                if (activity1.getFunctionattendancesum() > n) {
                    if (studentActivityService.insertSelective(studentActivity) > 0) {
                        Activity activity = new Activity();
                        activity.setFunctionattendance(n + 1);
                        activity.setActivityid(activityId);
                        studentActivityService.updateByPrimaryKeySelective(activity);
                        objectMap.put("message", "成功");
                        objectMap.put("code", 200);
                        if (n == 0) {
                            studentIntegralController.addIntegral(studentId, "addActivity", 4);
                        }
                    } else {
                        objectMap.put("message", "报名失败");
                        objectMap.put("code", 201);
                    }
                } else {
                    objectMap.put("message", "报名失败人数已满");
                    objectMap.put("code", 203);
                }
            } else {
                objectMap.put("message", "报名失败你已经报名过了");
                objectMap.put("code", 204);
            }
        } else {
            objectMap.put("code", 202);
            objectMap.put("message", "此用户没有权限做此操作");
        }
        return objectMap;
    }

    /**
     * 添加活动，发布活动
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public synchronized Object addActivity(HttpServletRequest request,
                                           @RequestParam(value = "files", required = false) MultipartFile[] files
            , @RequestParam(value = "file1", required = false) MultipartFile file1) throws ParseException {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String studentId = request.getParameter("studentId");
        String activityTitle = request.getParameter("activityTitle");
        String activityPictureURL = "";
        String activityPictureURLs = "";
        String activityTime = request.getParameter("activityTime");
        String activityLocation = request.getParameter("activityLocation");
        String activityType = "未审核";
        String activityContent = request.getParameter("activityContent");
        Integer functionAttendanceSum = Integer.parseInt(request.getParameter("functionAttendanceSum"));
        String activityCollegeNumber = request.getParameter("activityCollegeNumber");
//        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//        Date date=simpleDateFormat .parse(activityTime);
//        long timeStemp = date.getTime();
//        simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        activityTime = simpleDateFormat.format(timeStemp);
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null) {
            String activityCollege = studentApp.getStudentname();
            Activity activity = new Activity();
            activity.setAcitvitytitle(activityTitle);
            activity.setActivitycollege(activityCollege);
            activity.setActivitylocation(activityLocation);
            activity.setActivitytime(activityTime);
            activity.setActivitytype(activityType);
            activity.setActivitycontent(activityContent);
            activity.setActivitycollegenumber(activityCollegeNumber);
            activity.setFunctionattendancesum(functionAttendanceSum);
            activity.setActivitycollegeid(studentId);
            if (manageActivityService.selectByAll(activity) == null) {
                if (file1 == null) {
                    activity.setActivitypictureurl(activityPictureURL);
                } else {
                    if (!file1.getOriginalFilename().equals("")) {
                        String path = request.getSession().getServletContext().getRealPath("/") + "upload";
                        File targetFile;
                        String key = activityCollege + "-activity-" + file1.getOriginalFilename();
                        targetFile = new File(path, key);
                        if (!targetFile.exists()) {
                            targetFile.mkdirs();
                            try {
                                file1.transferTo(targetFile);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            targetFile.delete();
                            try {
                                file1.transferTo(targetFile);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        PictureUtil pictureUtil = new PictureUtil();
                        pictureUtil.zipWidthHeightImageFile(targetFile.getPath(), 720, 360, 4);
                        activityPictureURL = AliyunOssUtil.save(key, targetFile.getPath());
                        activity.setActivitypictureurl(activityPictureURL);
                        targetFile.delete();
                    }

                }
                if (files == null) {
                    activity.setActivitypictureurls(activityPictureURLs);
                } else {
                    MultipartFile file;
                    String url = "";
                    String path = request.getSession().getServletContext().getRealPath("/") + "upload";
                    File targetFile;
                    for (int i = 0; i < files.length; i++) {
                        file = files[i];
                        if (!file.getOriginalFilename().equals("")) {
                            String key = activityCollege + "-activity-" + file.getOriginalFilename();
                            targetFile = new File(path, key);
                            if (!targetFile.exists()) {
                                targetFile.mkdirs();
                                try {
                                    file.transferTo(targetFile);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                targetFile.delete();
                                try {
                                    file.transferTo(targetFile);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            PictureUtil pictureUtil = new PictureUtil();
                            pictureUtil.zipWidthHeightImageFile(targetFile.getPath(), 720, 360, 4);
                            activityPictureURL = AliyunOssUtil.save(key, targetFile.getPath());
                            if (i < files.length - 1) {
                                url = activityPictureURL + "," + url;
                            } else {
                                url = url + activityPictureURL;
                            }
                            targetFile.delete();
                        }
                    }
                    activity.setActivitypictureurls(url);
                }
                if (manageActivityService.insertSelective(activity) > 0) {
                    StudentCount studentCount = studentCountService.selectByPrimaryKey(studentId);
                    StudentCount studentCount1 = new StudentCount();
                    if (studentCount != null) {
                        studentCount1.setActivityaddnum(studentCount.getActivityaddnum() + 1);
                        studentCount1.setStudentid(studentId);
                        studentCountController.add(studentCount1, 1);
                    } else {
                        studentCount1.setActivityaddnum(1);
                        studentCount1.setStudentid(studentId);
                        studentCountController.add(studentCount1, 0);
                    }
                    objectMap.put("code", 200);
                    objectMap.put("message", "成功");
                } else {
                    objectMap.put("code", 201);
                    objectMap.put("message", "添加失败");
                }
            } else {
                objectMap.put("code", 202);
                objectMap.put("message", "请勿重复添加");
            }
        } else {
            objectMap.put("code", 203);
            objectMap.put("message", "此用户没有权限做此操作");
        }

        return objectMap;
    }

    /**
     * 查看活动参加的人
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectP")
    public synchronized
    @ResponseBody
    Object selectStudentActivityP(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        List<Map> mapList = new ArrayList<Map>();
        Map<String, Object> map;
        Integer activityId = Integer.parseInt(request.getParameter("activityId"));
        String studentId = request.getParameter("studentId");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null) {
            StudentActivity studentActivity = new StudentActivity();
            studentActivity.setActivityid(activityId);
            List<StudentActivity> studentActivityList = studentActivityService.countById(studentActivity);
            if (studentActivityList != null && studentActivityList.size() > 0) {
                for (int i = 0; i < studentActivityList.size(); i++) {
                    studentActivity = studentActivityList.get(i);
                    map = new HashMap<String, Object>();
                    Student stu = studentService.selectByPrimaryKey(studentActivity.getStuid());
                    map.put("studentId", studentActivity.getStuid());
                    map.put("studentName", stu.getStudentname());
                    map.put("studentClass", stu.getStudentclass());
                    mapList.add(map);
                }
                objectMap.put("data", mapList);
                objectMap.put("code", 200);
                objectMap.put("message", "成功");
            } else {
                objectMap.put("code", 201);
                objectMap.put("message", "此活动没有人参加");
            }
        } else {
            objectMap.put("code", 202);
            objectMap.put("message", "此用户没有权限做此操作");
        }
        return objectMap;
    }
}
